<template>
  <el-card>
    <div>
      <el-button
        type="danger"
        size="mini"
        class="del-more"
        @click="handleDelete(checkedIds)"
        >批量删除</el-button
      >
      <!--  列表 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="id" label="Id" width="180"> </el-table-column>
        <el-table-column prop="username" label="账户名称" width="180">
        </el-table-column>
        <el-table-column prop="group_id" label="账号权限">
          <template v-slot="{ row }">
            <el-tag v-if="row.group_id === 1">超级管理员</el-tag>
            <el-tag type="info" v-else>普通管理员</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button size="mini" @click="handleEdit(row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 编辑弹窗 -->
      <el-dialog
        title="账号编辑"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-form
          :model="accountForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              type="text"
              v-model="accountForm.username"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户权限" prop="group_id">
            <el-select v-model="accountForm.group_id" placeholder="用户权限">
              <el-option label="普通管理员" value="2"></el-option>
              <el-option label="高级管理员" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editAccount">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
import { userList, delUser, editUser } from '../../api/users.js'
export default {
  data() {
    var validateAccount = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名或账号或手机号'))
      } else {
        callback()
      }
    }

    var validateGroup = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择用户权限'))
      } else {
        callback()
      }
    }
    return {
      currentPage: 1,
      pageSize: 5,
      total: 0,
      tableData: [],
      multipleSelection: [],
      checkedIds: '',
      dialogVisible: false,

      accountForm: {
        username: '',
        group_id: ''
      },
      rules: {
        username: [{ validator: validateAccount, trigger: 'blur' }],
        group_id: [{ validator: validateGroup, trigger: 'change' }]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const users = JSON.parse(localStorage.getItem('users') || '{}')
      const { data, count } = await userList({
        member_id: users.member_id,
        access_token: users.access_token,
        page: this.currentPage,
        limit: this.pageSize
      })
      console.log(data)
      this.tableData = data
      this.total = count
    },
    handleEdit(o) {
      // console.log(index, row)
      // 解决了下拉框回写失败，因为数据格式问题
      // this.accountForm = o
      // o.group_id = o.group_id + ''
      // 解决了下拉框回写失败，因为数据格式的问题
      this.accountForm.group_id = this.accountForm.group_id + ''
      // 当前数据比较简单，可以使用JSON的方式
      this.accountForm = JSON.parse(JSON.stringify(o))
      this.dialogVisible = true
    },
    handleClose() {
      this.$refs.ruleForm.resetFields()
    },
    editAccount() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          // const token = localStorage.getItem('token')
          // const users = localStorage.getItem('users') || '{}'
          // const token = JSON.parse(users).access_token
          const users = JSON.parse(localStorage.getItem('users') || '{}')
          const { code, msg } = await editUser({
            // 引用数据类型的是给路径，需转为基本数据类型才是复制
            member_id: users.member_id,
            access_token: users.access_token,
            username: this.accountForm.username,
            group_id: this.accountForm.group_id - 0,
            id: this.accountForm.id
          })
          if (code === 1) {
            this.$message.success(msg)
            this.getUserList()
            this.dialogVisible = false
          } else {
            this.$message.error(msg)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleDelete(id) {
      // console.log(index, row)
      // let ids = ''
      // if (!flag) {
      //   // 单项删除
      //   ids = id
      // } else {
      //   // 批量删除
      //   // const arr = this.multipleSelection.map((item) => item.id)
      //   // console.log(arr)
      //   // ids = arr.join()
      // }
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 当用户点击确认删除的时候发出请求
          // this.$message({
          //   type: 'success',
          //   message: '删除成功!'
          // })
          const users = JSON.parse(localStorage.getItem('users') || '{}')
          const { code, msg } = await delUser({
            member_id: users.member_id,
            access_token: users.access_token,
            ids: id
          })
          if (code === 1) {
            this.$message.success(msg)
            this.getUserList()
          } else {
            this.$message.error(msg)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.currentPage = val
      this.getUserList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.checkedIds = this.multipleSelection.map((item) => item.id).join()
      console.log(this.checkedIds)
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  height: 100%;
  border: none;
  overflow-y: auto;
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }
  &::-webkit-scrollbar-thumb {
    border-radius: 20px;
    background: #eee;
    cursor: pointer;

    &:hover {
      background: #bebebe;
    }

    &:active {
      background: #b0b0b0;
    }
  }
  .el-pagination {
    margin-top: 50px;
  }
  .el-aside {
    background-color: #10042a;
    overflow-x: hidden;

    &::-webkit-scrollbar {
      display: none; // 重点
      -webkit-overflow-scrolling: touch;
    }
  }
  .del-more {
    margin-top: 10px;
    margin-bottom: 10px;
  }
  .el-input {
    width: 200px;
  }
}
</style>
